import React, { useState, useRef } from 'react'
import { Table, Button, Modal, Form, message, Input } from 'antd'
import { useNavigate } from 'react-router-dom'
import PopoverColumn from '~/components/popover-column'
import { viewAttachmentList, AttachmentDeletion, getAttachHttpUrl } from '~/api/query-api'
import { formatTime } from '~/utils/utils'

const colums: any = ({
  handleNavToProperty,
  isSwitchAttachmentList,
  setIsShowDeleteReason,
  recordData,
  onClickDownLoadFile
}: any) =>
  isSwitchAttachmentList
    ? [
        {
          title: '序号',
          dataIndex: 'id',
          align: 'center',
          render: (_: any, record: any, index: number) => `${index + 1}`
        },
        {
          title: '上传人',
          dataIndex: 'createUserName',
          align: 'center'
        },
        {
          title: '案件名称',
          dataIndex: 'caseName',
          align: 'center',
          render: (caseName: any, record: any) => (
            <PopoverColumn record={record}>
              <a>{caseName}</a>
            </PopoverColumn>
          )
        },
        {
          title: '上传单位',
          dataIndex: 'createCompanyName',
          align: 'center',
          key: 'age'
        },
        {
          title: '上传部门',
          dataIndex: 'createDepartmentName',
          align: 'center',
          key: 'age'
        },
        {
          title: '上传时间',
          dataIndex: 'createTime',
          align: 'center',
          key: 'age',
          render: (createTime: any) => <div>{formatTime(createTime)}</div>
        },
        {
          title: '文件名',
          dataIndex: 'fileName',
          align: 'center',
          key: 'age'
        },
        {
          title: '操作',
          dataIndex: 'age4',
          align: 'center',
          key: 'age',
          render: (_: any, record: any) => (
            <>
              <Button type="primary" size="small" onClick={() => onClickDownLoadFile(record)}>
                下载
              </Button>
              <Button
                style={{ marginLeft: 10 }}
                type="primary"
                size="small"
                onClick={() => {
                  setIsShowDeleteReason(true)
                  recordData.current = record
                }}
              >
                删除
              </Button>
            </>
          )
        }
      ]
    : [
        {
          title: '序号',
          dataIndex: 'id',
          align: 'center',
          render: (_: any, record: any, index: number) => `${index + 1}`
        },
        {
          title: '案件编号',
          dataIndex: 'caseNo',
          align: 'center',
          render: (caseNo: any, record: any) => (
            <PopoverColumn record={record}>
              <a>{caseNo}</a>
            </PopoverColumn>
          )
        },
        {
          title: '案件名称',
          dataIndex: 'caseName',
          align: 'center',
          render: (caseName: any, record: any) => (
            <PopoverColumn record={record}>
              <a>{caseName}</a>
            </PopoverColumn>
          )
        },
        {
          title: '办案单位',
          dataIndex: 'caseCompanyName',
          align: 'center',
          key: 'age'
        },
        {
          title: '办案部门',
          dataIndex: 'caseDepartmentName',
          align: 'center',
          key: 'age'
        },
        {
          title: '操作',
          dataIndex: 'age4',
          align: 'center',
          key: 'age',
          render: (_: any, record: any) => (
            <>
              <Button
                type="primary"
                size="small"
                onClick={() => handleNavToProperty({ ...record, isShowAddFiles: true })}
              >
                添加附件
              </Button>
              <Button
                style={{ marginLeft: 10 }}
                type="primary"
                size="small"
                onClick={() => handleNavToProperty({ ...record, isShowAddFiles: false })}
              >
                查看附件
              </Button>
            </>
          )
        }
      ]

const MoveList = ({ moveList }: any) => {
  const recordData = useRef({ storeId: '', fileName: '', caseNo: '', caseName: '' })
  const [attachmentList, setAttachmentList] = useState([])
  const [isSwitchAttachmentList, setIsSwitchAttachmentList] = useState(false)
  const [form] = Form.useForm()
  const navigate = useNavigate()
  const [isShowDeleteReason, setIsShowDeleteReason] = useState(false)

  const handleNavToProperty = (record: any) => {
    console.log('查看', record)
    /**
     * caseState   1:未移送 2:未告知  3:已移送 4:已告知
     */

    navigate('/updating-files-deatil', { state: record })
  }

  const getAttachmentList = async () => {
    const value = form.getFieldValue('classification')
    const { data } = await viewAttachmentList({ fileCategory: value, caseNo: recordData.current.caseNo })
    setAttachmentList(data)
  }

  const onClickAddAttachmentList = (record: any) => {
    recordData.current = record
  }

  const onClickInitValue = () => {
    setIsSwitchAttachmentList(false)
  }

  const onClickDeleteReason = async () => {
    await AttachmentDeletion({ storeId: recordData.current.storeId, deleteReason: form.getFieldValue('deleteReason') })
    message.success(`删除${recordData.current.fileName}成功`)
    getAttachmentList()
    setIsShowDeleteReason(false)
  }

  const onClickDownLoadFile = async (record: any) => {
    const { data } = await getAttachHttpUrl({ storeId: record.storeId })
    const image = new Image()
    // 解决跨域 Canvas 污染问题
    image.setAttribute('crossOrigin', 'anonymous')
    image.onload = function() {
      const canvas = document.createElement('canvas')
      canvas.width = image.width
      canvas.height = image.height

      const context = canvas.getContext('2d')
      context!.drawImage(image, 0, 0, image.width, image.height)
      const url = canvas.toDataURL('image/png')

      // 生成一个a元素
      const a = document.createElement('a')
      // 创建一个单击事件
      const event = new MouseEvent('click')

      // 将a的download属性设置为我们想要下载的图片名称，若name不存在则使用‘下载图片名称’作为默认名称
      a.download = record.name || '下载图片名称'
      // 将生成的URL设置为a.href属性
      a.href = url
      // 触发a的单击事件
      a.dispatchEvent(event)
    }

    image.src = data
  }

  return (
    <div>
      <Table
        pagination={{
          size: 'default',
          total: moveList.length,
          showSizeChanger: true,
          showQuickJumper: true,
          showTotal: total => `共 ${total} 条`
        }}
        rowKey={isSwitchAttachmentList ? 'id' : 'caseNo'}
        bordered
        dataSource={isSwitchAttachmentList ? attachmentList : moveList}
        columns={colums({
          handleNavToProperty,
          onClickAddAttachmentList,
          isSwitchAttachmentList,
          setIsShowDeleteReason,
          recordData,
          onClickDownLoadFile
        })}
      />
      {isSwitchAttachmentList && (
        <Button style={{ margin: '10px auto', display: 'flex' }} onClick={onClickInitValue}>
          返回
        </Button>
      )}

      <Modal
        visible={isShowDeleteReason}
        onOk={onClickDeleteReason}
        onCancel={() => {
          setIsShowDeleteReason(false)
        }}
      >
        <Form validateTrigger="onBlur" form={form} style={{ marginTop: 36 }}>
          <Form.Item name="deleteReason" label="删除原因">
            <Input />
          </Form.Item>
          {/* {isShowRemark && (
            <Form.Item name="whereaboutsRemark" label="备注">
              <TextArea placeholder="请输入备注" />
            </Form.Item>
          )} */}
        </Form>
      </Modal>
    </div>
  )
}

export default MoveList
